package com.thomas.qiaolr;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.thomas.model.ImageModel;
import com.thomas.tool.ImageUtil;

/**
 * 从 www.shaimn.com 下载图片
 * @author thomas
 *
 */
public class DownloadImagesFromQiaolr {
	
	/**
	 * 根据类别保存图片
	 * @param id
	 * @return
	 */
	public static boolean saveImageByCategoryId(String id) {

		// http://qiaolr.com/view/2485.html
		// http://qiaolr.com/view/3921.html

		String siteBaseUrl  = "http://www.qiaolr.com";
		String pageUrl = siteBaseUrl + "/view/" + id + ".html";
		
		try {
			String userAgent = "Firefox/45.0.2454.81 Safari/537.36";
			Document doc = Jsoup.connect(pageUrl).timeout(36000).userAgent(userAgent).get();
			String title = doc.title().split("_")[0];
			String saveName = id + "_" + title + ".jpg";
			String imageUrl = siteBaseUrl + doc.select(".picbox>img").attr("src");
			
			ImageModel imageModel = new ImageModel();
			imageModel.setImageUrl(imageUrl);
			imageModel.setImageName(saveName);
			
			return ImageUtil.saveImageByImageModel(imageModel);
		} catch (Exception e) {
			return false;
		}

	}
	
	/**
	 * 保存图片线程
	 * @param i 类别ID
	 */
	public static void save(String i) {
		
		boolean isSuccess = DownloadImagesFromQiaolr.saveImageByCategoryId(i+"");
		
		if (isSuccess != true) {
			System.out.println("skip "+i+" ...");
			return;
		}
		
		for (int k=2; k<99; k++) {
			new SaveImageThreadTool(i+"_"+k).start();
		}
	}
	
	/**
	 * 执行的主函数
	 * @param args
	 */
	public static void main(String[] args) {
		
		// min = 1
		// cur = 75
		// max = 9999
		for (int i=81; i<84; i++) {
			DownloadImagesFromQiaolr.save(i+"");
		}
	}
}


//保存图片线程
class SaveImageThreadTool extends Thread {
	
	private String saveCateId = "";

	public SaveImageThreadTool(String saveCateId) {
		super();
		this.saveCateId = saveCateId;
	}

	public void run() {
		DownloadImagesFromQiaolr.saveImageByCategoryId(this.saveCateId);
	}
	
}
